package cn.cool.infrastructure.adapter.repository;

import cn.cool.infrastructure.dcc.DCCService;
import cn.cool.infrastructure.redis.IRedisService;
import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;

import javax.annotation.Resource;
import java.util.function.Supplier;

@Slf4j
public abstract class AbstractRepository {
    @Resource
    private IRedisService redisService;

    @Resource
    private DCCService dccService;

    protected <T> T getFromCacheOrDb(String cacheKey, Supplier<T> dbFallback) {
        // 判断是否开启缓存
        if (dccService.isCacheOpenSwitch()) {
            // 从缓存获取
            T cacheResult = null;
            try {
                cacheResult = redisService.getValue(cacheKey);
            } catch (Throwable throwable) {
                return dbFallback.get();
            }
            // 缓存存在数据直接走缓存
            if (ObjUtil.isNotNull(cacheResult)) {
                return cacheResult;
            }
            // 缓存不存在就查询db
            T dbResult = dbFallback.get();
            // 数据库查询结果为空，则直接返回
            if (ObjUtil.isNull(dbResult)) {
                return null;
            }
            // 写入缓存
            redisService.setValue(cacheKey, dbResult);
            return dbResult;
        } else {
            log.warn("缓存降级，直接从数据库读取数据: {}", cacheKey);
            return dbFallback.get();
        }
    }

}
